package cn.school.demo.ui.point_ranking

import android.annotation.SuppressLint
import android.graphics.Color
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentPointRankingBinding
import cn.school.demo.pojo.Leaderboard
import cn.school.demo.pojo.User

class PointRankingFragment : Fragment() {

    private lateinit var viewModel: PointRankingViewModel
    private lateinit var binding: FragmentPointRankingBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        viewModel = ViewModelProvider(this).get(PointRankingViewModel::class.java)
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_point_ranking, container, false)
        binding.vw = this
        binding.my = MyApplication
        binding.lifecycleOwner = viewLifecycleOwner
        init()
        return binding.root
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    private fun init() {
        viewModel.getTotalIntegralRanking().observe(viewLifecycleOwner) {
            if (it["userList"] != null && it["leaderboard"] != null) {
                viewModel.updateUserList(it["userList"] as MutableList<User>)
                viewModel.setLeaderboard(it["leaderboard"] as Leaderboard)
            } else {
                viewModel.updateUserList(mutableListOf())
                viewModel.setLeaderboard(Leaderboard())
            }
            binding.pointRankingFragmentPeopleList.apply {
                adapter?.notifyDataSetChanged() ?: let {
                    layoutManager = LinearLayoutManager(requireContext())
                    adapter = PointRankingAdapter(viewModel.userList)
                }
            }
            updateUI()
        }
        viewModel.getYearIntegralRanking().observe(viewLifecycleOwner) {
            if (it["userList"] != null && it["leaderboard"] != null) {
                viewModel.updateUserListTwo(it["userList"] as MutableList<User>)
                viewModel.setLeaderboardTwo(it["leaderboard"] as Leaderboard)
            } else {
                viewModel.updateUserListTwo(mutableListOf())
                viewModel.setLeaderboard(Leaderboard())
            }
        }
    }

    fun gotoMy() = findNavController().navigate(R.id.action_PointRanking_to_My)

    @SuppressLint("NotifyDataSetChanged")
    fun clickAllIntegralButton() {
        binding.pointRankingFragmentYearIntegralButton.apply {
            setBackgroundResource(R.drawable.button_shape_ranking_red_right)
            setTextColor(Color.WHITE)
        }
        binding.pointRankingFragmentAllIntegralButton.apply {
            setTextColor(Color.RED)
            setBackgroundResource(R.drawable.button_shape_ranking_white_left)
        }
        if (viewModel.click == 1 && viewModel.userList.size != 0 && viewModel.userListByUser.size != 0) {
            val list = mutableListOf<User>()
            list.addAll(viewModel.userList)
            viewModel.updateUserList(viewModel.userListByUser)
            viewModel.updateUserListTwo(list)
            binding.pointRankingFragmentPeopleList.adapter?.notifyDataSetChanged()
            val l = viewModel.leaderboard.value
            viewModel.setLeaderboard(viewModel.leaderboardByUser.value!!)
            viewModel.setLeaderboardTwo(l!!)
            viewModel.setClick(0)
            updateUI()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun clickYearIntegralButton() {
        binding.pointRankingFragmentAllIntegralButton.apply {
            setTextColor(Color.WHITE)
            setBackgroundResource(R.drawable.button_shape_ranking_red_left)
        }
        binding.pointRankingFragmentYearIntegralButton.apply {
            setBackgroundResource(R.drawable.button_shape_ranking_white_right)
            setTextColor(Color.RED)
        }
        if (viewModel.click == 0 && viewModel.userList.size != 0 && viewModel.userListByUser.size != 0) {
            val list = mutableListOf<User>()
            list.addAll(viewModel.userList)
            viewModel.updateUserList(viewModel.userListByUser)
            viewModel.updateUserListTwo(list)
            binding.pointRankingFragmentPeopleList.adapter?.notifyDataSetChanged()
            val l = viewModel.leaderboard.value
            viewModel.setLeaderboard(viewModel.leaderboardByUser.value!!)
            viewModel.setLeaderboardTwo(l!!)
            viewModel.setClick(1)
            updateUI()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateUI() {
        binding.apply {
            pointRankingFragmentPeopleNum.text = "本组共${viewModel.userList.size}人参与排名"
            pointRankingFragmentClassText.text =
                "${viewModel.leaderboard.value!!.teamRanking}\n您在班级的排名"
            pointRankingFragmentMajorText.text =
                "${viewModel.leaderboard.value!!.majorRanking}\n您在专业的排名"
            pointRankingFragmentCollageText.text =
                "${viewModel.leaderboard.value!!.collegeRanking}\n您在全院的排名"
            pointRankingFragmentSchoolText.text =
                "${viewModel.leaderboard.value!!.universityRanking}\n您在全校的排名"
        }
    }

    private inner class PointRankingHolder(view: View) : RecyclerView.ViewHolder(view) {
        private lateinit var user: User
        private val numTextView =
            itemView.findViewById<TextView>(R.id.list_item_point_ranking_number)
        private val nameTextView =
            itemView.findViewById<TextView>(R.id.list_item_point_ranking_name)
        private val pointTextView =
            itemView.findViewById<TextView>(R.id.list_item_point_ranking_point)
        private val imageView =
            itemView.findViewById<ImageView>(R.id.list_item_point_ranking_image_view)

        @SuppressLint("SetTextI18n")
        fun bind(user: User, position: Int) {
            this.user = user
            pointTextView.text = "${this.user.totalIntegral}分"
            when (position) {
                0 -> numTextView.setTextColor(resources.getColorStateList(R.color.red, null))
                1 -> numTextView.setTextColor(
                    resources.getColorStateList(
                        R.color.orange,
                        null
                    )
                )
                2 -> numTextView.setTextColor(resources.getColorStateList(R.color.teal_200, null))
                else -> numTextView.setTextColor(resources.getColorStateList(R.color.black, null))
            }
            numTextView.text = (position + 1).toString()
            nameTextView.text = this.user.nickname
            MyApplication.setCircleGlideByUrlString(
                requireContext(),
                this.user.headPortrait,
                imageView
            )
        }
    }

    private inner class PointRankingAdapter(var userList: MutableList<User>) :
        RecyclerView.Adapter<PointRankingHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PointRankingHolder {
            val view = layoutInflater.inflate(R.layout.list_item_point_ranking, parent, false)
            return PointRankingHolder(view)
        }

        override fun onBindViewHolder(holder: PointRankingHolder, position: Int) {
            val user = userList[position]
            holder.bind(user, position)
        }

        override fun getItemCount() = userList.size
    }
}